import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'provider/AuthProvider.dart';
import 'provider/UserProvider.dart';
import 'provider/post_list_provider.dart';
import 'utils/router.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final authProvider = AuthProvider();
  await authProvider.init(); // 初始化加载token、登录态等

  // 初始化全局路由，依赖authProvider管理登录态重定向
  initGlobalRouter(authProvider);

  // 全局错误监听
  FlutterError.onError = (details) {
    authProvider.handleApiError(details.exception);
    FlutterError.presentError(details);
  };

  // 捕获平台层未处理异常
  PlatformDispatcher.instance.onError = (error, stack) {
    authProvider.handleApiError(error);
    return true;
  };

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<AuthProvider>.value(value: authProvider),
        ChangeNotifierProvider(create: (_) => PostListProvider()),
        ChangeNotifierProvider(create: (_) => UserProvider()),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: globalRouter,
      debugShowCheckedModeBanner: false,
      title: '小书A',
      theme: ThemeData(
        primaryColor: Colors.white, // 纯白色主色
        scaffoldBackgroundColor: Colors.white, // 背景白色
        visualDensity: VisualDensity.adaptivePlatformDensity,
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.white, // 白色背景
          foregroundColor: Colors.black, // 标题和图标颜色为黑色
          elevation: 0, // 去掉阴影，按需设置
          systemOverlayStyle: SystemUiOverlayStyle(
            statusBarColor: Colors.white,
            statusBarIconBrightness: Brightness.dark, // 状态栏图标颜色（黑）
          ),
        ),
      ),
    );
  }
}
